﻿@using System.Diagnostics.CodeAnalysis
@using JxAudio.TransVo
@using Microsoft.Extensions.Localization

@inject IStringLocalizer<PlaylistDialog> StringLocalizer
@inject HttpClient Http
@inject DialogService DialogService

<ValidateForm Model="Playlist" OnValidSubmit="OnValidSubmit">
    <div class="row g-3">
        <div class="col-6">
            <BootstrapInput @bind-Value="@Playlist.Name" ShowLabel="true"></BootstrapInput>
        </div>
        <div class="col-6">
            <Switch @bind-Value="@Playlist.IsPublic" ShowLabel="true"></Switch>
        </div>
        <div class="col-12">
            <Textarea rows="1" @bind-Value="@Playlist.Description" ShowLabel="true"></Textarea>
        </div>
        <div class="col-12" style="height: 55vh">
            <TrackTable Tracks="Playlist.Songs" ShowDefaultButton="false">
                <TrackButton>
                    <TableCellButton Icon="fas fa-minus" OnClick="() => Minus(context)"></TableCellButton>
                </TrackButton>
                <ToolbarButtons>
                    <TableToolbarButton TItem="TrackVo" Text="@StringLocalizer["AddTrack"]" Icon="fa fa-plus" OnClick="AddTrack"></TableToolbarButton>
                </ToolbarButtons>
            </TrackTable>
        </div>
    </div>
    <div class="modal-footer">
        <DialogCloseButton></DialogCloseButton>
        <Button Icon="fa fa-save" Text="@StringLocalizer["Save"]" ButtonType="ButtonType.Submit"></Button>
    </div>
</ValidateForm>

@code {
    [NotNull]
    [Parameter]
    public PlaylistVo? Playlist { get; set; }
    
    [CascadingParameter]
    private Func<Task>? OnCloseAsync { get; set; }

    protected override void OnInitialized()
    {
        base.OnInitialized();
        Playlist ??= new PlaylistVo();
    }

    private void Minus(TrackVo trackVo)
    {
        Playlist.Songs?.Remove(trackVo);
    }

    private async Task OnValidSubmit(EditContext arg)
    {
        if (Playlist.Id is null or 0)
        {
            await Http.PostAsJsonAsync($"api/Playlist/CreatePlayList", Playlist);
        }
        else
        {
            await Http.PostAsJsonAsync($"api/Playlist/UpdatePlayList", Playlist);
        }

        if (OnCloseAsync != null)
        {
            await OnCloseAsync();
        }
    }

    private async Task AddTrack(MouseEventArgs obj)
    {
        var tracks = Playlist.Songs ?? new List<TrackVo>();
        var ret = await DialogService.ShowModal<TrackSearch>(new ResultDialogOption()
        {
            Title = StringLocalizer["AddTrack"],
            ComponentParameters = new Dictionary<string, object>()
            {
                [nameof(TrackSearch.SelectedTracks)] = tracks
            }
        });
        if (ret == DialogResult.Yes)
        {
            Playlist!.Songs = tracks;
        }
    }

}